/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.service.impl.section;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.encrypt.utils.EncryptUtils;
import com.comac.ins.isfd.constant.enums.IsfdSectionTypeEnum;
import com.comac.ins.isfd.domain.IsfdSection;
import com.comac.ins.isfd.domain.IsfdSectionResult;
import com.comac.ins.isfd.domain.bo.IsfdSectionBo;
import com.comac.ins.isfd.domain.vo.IsfdLayupEquivalentMaterialVo;
import com.comac.ins.isfd.util.SectionCalculateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 型材库 复材浮框 实现类
 *
 * @author hxloongs
 * @date 2024-7-30
 */
@Slf4j
@Service
public class IsfdSectionFzffServiceImpl extends IsfdAbstractSectionService {
    @Override
    public String selectByType() {
        return IsfdSectionTypeEnum.FZFF.getValue();
    }

    @Override
    public double[] calculate(IsfdSectionBo isfdSectionBo) {
        String tLayerCode = isfdSectionBo.getTLayerCode();

        IsfdLayupEquivalentMaterialVo isfdLayupEquivalentMaterialVo = iIsfdLayupEquivalentMaterialService.queryByLayCode(tLayerCode);

        double[][] layerParametersFZ = {{isfdLayupEquivalentMaterialVo.getT(), isfdLayupEquivalentMaterialVo.getExx(), isfdLayupEquivalentMaterialVo.getGxy()}};
        double[] shapeParametersFZ = {isfdSectionBo.getW1(), isfdSectionBo.getH(), isfdSectionBo.getW2(), isfdSectionBo.getR()};
        double[] sectionPropertiesFZ = new double[8];
        SectionCalculateUtils.calculateFzProfile(layerParametersFZ, shapeParametersFZ, sectionPropertiesFZ);
        sectionPropertiesFZ[6] = isfdLayupEquivalentMaterialVo.getRho(); // rho
        sectionPropertiesFZ[7] = isfdLayupEquivalentMaterialVo.getX(); // thm
        return sectionPropertiesFZ;
    }

    @Transactional
    @Override
    public Boolean save(IsfdSectionBo bo) {
        // 1. 参数校验
        checkParamsReSetBo(bo);

        // 2. 获取hash字段
        String hashUniqueKey = EncryptUtils.hashFields(bo.getType(), bo.getSerialNumber(), bo.getAttributeNumber(), bo.getMat1Id(),
            bo.getW1(), bo.getH(), bo.getW2(), bo.getTLayerCode(), bo.getBotOuterDistance());

        // 3. 幂等校验
        Boolean isUpdate = super.checkUnique(bo, hashUniqueKey);

        // 4. 计算
        double[] sectionPropertiesFZ = this.calculate(bo);

        // 5. 落表
        IsfdSection isfdSection = MapstructUtils.convert(bo, IsfdSection.class);
        isfdSection.setHashUniqueKey(hashUniqueKey);
        isfdSection.setRho(sectionPropertiesFZ[6]);
        isfdSection.setThm(sectionPropertiesFZ[7]);
        // 判断是新增业务还是修改业务，处理落表的方式不同
        if (isUpdate) {
            isfdSectionMapper.updateById(isfdSection);
            IsfdSectionResult isfdSectionResult = isfdSectionResultMapper.selectOne(new LambdaQueryWrapper<IsfdSectionResult>()
                .eq(IsfdSectionResult::getSecId, isfdSection.getId()));
            if (isfdSectionResult == null) {
                throw new BaseException("修改时，发现对应结果记录不存在，请确认后重试！");
            }
            isfdSectionResult.setE(sectionPropertiesFZ[0]);
            isfdSectionResult.setG(sectionPropertiesFZ[1]);
            isfdSectionResult.setXc(sectionPropertiesFZ[2]);
            isfdSectionResult.setA(sectionPropertiesFZ[3]);
            isfdSectionResult.setI1(sectionPropertiesFZ[4]);
            isfdSectionResult.setI2(sectionPropertiesFZ[5]);
            isfdSectionResultMapper.updateById(isfdSectionResult);
        } else {
            isfdSectionMapper.insert(isfdSection);
            IsfdSectionResult isfdSectionResult = new IsfdSectionResult();
            isfdSectionResult.setSecId(isfdSection.getId());
            isfdSectionResult.setE(sectionPropertiesFZ[0]);
            isfdSectionResult.setG(sectionPropertiesFZ[1]);
            isfdSectionResult.setXc(sectionPropertiesFZ[2]);
            isfdSectionResult.setA(sectionPropertiesFZ[3]);
            isfdSectionResult.setI1(sectionPropertiesFZ[4]);
            isfdSectionResult.setI2(sectionPropertiesFZ[5]);
            isfdSectionResultMapper.insert(isfdSectionResult);
        }
        return Boolean.TRUE;
    }


    private void checkParamsReSetBo(IsfdSectionBo isfdSectionBo) {
        if (StringUtils.isBlank(isfdSectionBo.getSerialNumber()) || !isfdSectionBo.getSerialNumber().startsWith(IsfdSectionTypeEnum.FZ.getValue())) {
            throw new BaseException("编号不能为空或者格式不正确（需要FZ开头），请确认后重试！");
        }
        if (StringUtils.isBlank(isfdSectionBo.getAttributeNumber())) {
            throw new BaseException("属性号不能为空，请确认后重试！");
        }
        if (StringUtils.isBlank(isfdSectionBo.getMat1Id())) {
            throw new BaseException("材料编号不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getH() == null) {
            throw new BaseException("h不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getW2() == null) {
            throw new BaseException("w2不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getR() == null) {
            throw new BaseException("r不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getTLayerCode() == null) {
            throw new BaseException("t铺层代号不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getBotOuterDistance() == null) {
            throw new BaseException("框底边到外形面距离 不能为空，请确认后重试！");
        }

        if (isfdSectionBo.getW1() == null) {
            throw new BaseException("w1 不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getThickness() == null) {
            throw new BaseException("厚度 不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getSRectangularSeg() == null) {
            throw new BaseException("矩型段面积 不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getSArcuateSeg() == null) {
            throw new BaseException("弧形段面积 不能为空，请确认后重试！");
        }
        if (isfdSectionBo.getSCorrectSeg() == null) {
            throw new BaseException("正确总面积 不能为空，请确认后重试！");
        }
//        // 处理W1 、厚度 、矩型段面积 、弧形段面积、正确总面积(给H列也没用，参数化计算后程序会重算面积)
//        String tLayerCode = isfdSectionBo.getTLayerCode();
//        Double number = null;
//        try {
//            number = Double.parseDouble(tLayerCode.substring(0, 2));
//            // =MID(O94,1,2)*0.187
//            isfdSectionBo.setW1(number * 0.187);
//            // =MID(O94,1,2)*0.187
//            isfdSectionBo.setThickness(number * 0.187);
//            // =(L94-N94-T94+M94-N94-T94)*T94
//            isfdSectionBo.setSRectangularSeg((isfdSectionBo.getH() - isfdSectionBo.getR() - isfdSectionBo.getThickness()
//                    + isfdSectionBo.getW2() - isfdSectionBo.getR() - isfdSectionBo.getThickness()) * isfdSectionBo.getThickness());
//            // =(3.1415926*(N94+T94)^2-3.1415926*(N94)^2)/4
//            isfdSectionBo.setSArcuateSeg((3.1415926 * Math.pow((isfdSectionBo.getR() + isfdSectionBo.getThickness()), 2)
//                    - 3.1415926 * Math.pow(isfdSectionBo.getR(), 2)) / 4);
//            // =U94+V94
//            isfdSectionBo.setSCorrectSeg(isfdSectionBo.getSRectangularSeg() + isfdSectionBo.getSArcuateSeg());
//        } catch (Exception e) {
//            log.error("取值失败", e);
//            throw new BaseException("w1/厚度/矩型段面积/弧形段面积/正确总面积 取值失败，请确认t铺层代号格式填写是否正确，以及其他参数是否填写正确！");
//        }
    }
}
